package com.three.iot.rest.shiro;

import com.three.iot.api.LoginInfoService;
import com.three.iot.commons.po.UserInfo;
import com.three.iot.commons.po.UserPermit;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author luiz
 * @Title: MyShiroRealm
 * @ProjectName csuser
 * @Description: TODO
 * @date 2018/10/26 14:36
 */
public class MyShiroRealm extends AuthorizingRealm {

    private static final Logger logger = LoggerFactory.getLogger(MyShiroRealm.class);
    @Resource
    private LoginInfoService iTkLoginInfoService;

    public MyShiroRealm() {
    }

    @Override
    public AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        UserInfo user = (UserInfo) SecurityUtils.getSubject().getPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //根据用户ID查询角色（role），放入到Authorization里。
        List<String> groupList = user.getUerGroups();
        Set<String> groupSet = new HashSet<String>();
        for (String groupNo : groupList) {
            groupSet.add(groupNo);
        }
        info.setRoles(groupSet);
        //根据用户ID查询权限（permission），放入到Authorization里。
        List<UserPermit> permissionList = user.getUserPermits();
        Set<String> permissionSet = new HashSet<String>();
        for (UserPermit permission : permissionList) {
            permissionSet.add(permission.getSourceNo());
        }
        logger.info("当前用户拥有的权限为:{}", permissionSet);
        info.setStringPermissions(permissionSet);
        return info;
    }


    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //存放登录信息
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        String loginNo = usernamePasswordToken.getUsername();
        String loginPass = new String(usernamePasswordToken.getPassword());
        com.three.iot.commons.enums.Result loginResult = iTkLoginInfoService.findByLoginNo(loginNo);
        if (loginResult.isSuccess()) {
            //放入shiro.调用CredentialsMatcher检验密码 已经校验过了 直接传值给Shiro
            return new SimpleAuthenticationInfo(loginResult.getData(), loginPass, loginNo);
        }
        return null;
    }
}
